import store from "@/store";
import axios from "axios";
import { Loading } from 'element-ui'

let loading = {
    loadingInstance: null,
    open: function(){
        if(this.loadingInstance == null){
            this.loadingInstance = Loading.service({
                target: '.main',
                background: 'rgba(0, 0, 0, 0.7)',
                text: '加载中...',
                spinner: 'el-icon-loading'
            })
        }
    },
    close: function() {
        if(this.loadingInstance !== null){
            this.loadingInstance.close()
        }
        this.loadingInstance = null
    }
}

let request = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000,
})


// 添加请求拦截器
request.interceptors.request.use(function (config) {
    let token = store.state.token
    config.headers.token = token
    loading.open()
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    loading.close()
    // 对请求错误做些什么
    return Promise.reject(error);
});



// 添加响应拦截器
request.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    loading.close()
    return response;
}, function (error) {
    // 对响应错误做点什么
    loading.close()
    return Promise.reject(error);
});



export default request